# 图像处理 --> 动物
import base64

import requests


def get_animal(download_path, access_token):
    '''
    动物识别
    '''
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"
    # 二进制方式打开图片文件
    f = open(download_path[0], 'rb')
    img = base64.b64encode(f.read())

    params = {"image": img}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        rs = response.json()
        # print(response.json())
        # 读取数据
        strover = '识别结果：\n'
        try:
            i = 1
            for animal in rs['result']:
                strover += '{}.动物名称：{}    Score：{:.6}\n'.format(i, animal['name'], animal['score'])
                i += 1
            message = "识别完成！！！"
        except Exception as e:
            strover += '解析错误, 请重试！！！'
            message = "识别出现问题！！！"
        # 把结果显示到控件
        finally:
            return strover, message
